const uuid = function () {
  function S4() {
    return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);
  }
  return (S4() + S4() + S4() + S4() + S4() + S4() + S4() + S4());
}
const toHexString = function(str) {
  if (!str)
    return "";
  var hexes = [];
  for (var i = 0; i < str.length; i++) {
    hexes.push("0x");
    hexes.push((str.charCodeAt(i)).toString(16));
  }
  return hexes.join("");
}
const dict = {
  map: {},
  org: {},
  category: {},
  itemsMap: {},
  init:function(app,config){
    let that = this;
    if (!app.globalData.dict){
      const getData = (url, param) => {
        return new Promise((resolve, reject) => {
          wx.request({
            url: url,
            method: 'GET',
            data: param,
            success(res) {
              resolve(res.data.data)
            },
            fail(err) {
              reject(err)
            }
          })
        })
      };
      getData(`${config.host}rest/sys/dict`,{}).then(data=>{
        if (app.globalData.dict) return;
        for (var i = 0; data&&i < data.length; i++) {
          let classId = data[i].classId;
          let className = data[i].className;
          let itemKey = data[i].itemKey;
          let itemValue = data[i].itemValue;
          
          if (!that.itemsMap[classId]) that.itemsMap[classId] = {};
          that.itemsMap[classId].name = className;
          if (!that.itemsMap[classId].items) that.itemsMap[classId].items = [];
          that.itemsMap[classId].items.push({ name: itemValue, value: itemKey });

          that.map[classId + '_' + itemKey] = itemValue;
          if (classId.startsWith("_org")) {
            that.org[itemKey] = itemValue;
          }
          if (classId.startsWith("_category")) {
            that.category[itemKey] = itemValue;
          }
        }
        app.globalData.dict = that;
      });
    }else{
      that = app.globalData.dict;
    }
    return that;
  },
  add: function (classId, items) {
    if (items) {
      for (let i = 0; i < items.length; i++) {
        this.map[classId + '_' + items[i].id] = items[i].name;
      }
      this.itemsMap[classId] = items;
    }
  },
  get: function (classId) {
    return this.itemsMap[classId];
  },
  transfer: function (classId, id) {
    return this.map[classId + '_' + id];
  }
}
const request = options => {
  let url = options.url;
  const app = getApp();
  if(app.globalData.user){
    const token = `${app.globalData.user.token}`;
    if (url.indexOf("?") != -1) {
      if (url.indexOf('&_token=') == -1 && url.indexOf('?_token=') == -1) url += "&_token=" + token;
    } else {
      url += "?_token=" + token;
    }
  }
  options.url=url;

  if (options.data && options.data.condition && !options.data.condition.startsWith('0x')){
    console.log(options.data.condition);
    options.data.condition = toHexString(options.data.condition);
  }

  const success = options.success ? options.success:()=>{};
  options.success = res =>{
    //token超时
    if (res && res.data && res.data.ok==false && res.data.code==500){
      wx.redirectTo({
        url: '/pages/auth/login'
      })
      return;
    }
    success(res);
  };
  wx.request(options);
};
const isEmpty = obj => {
  if (obj == "undefined" || obj == null || obj == "") {
    return true;
  } else {
    return false;
  }
};
const isNotEmpty = obj => {
  if (obj == "undefined" || obj == null || obj == "") {
    return false;
  } else {
    return true;
  }
};

const getNextFormatDate = function(str) {
	const date = new Date();
	date.setDate(date.getDate() + new Number(str));
	let year = date.getFullYear();
	let month = date.getMonth()+1;
	let day = date.getDate();
	if(month >= 1 && month <= 9) {
        month = "0" + month;
    }
	if(day >= 0 && day <= 9) {
		day = '0' + day;
	}
	return  year+"-"+ month+"-"+day;
}
const getNextFormatNowDate = function(str,days) {
	const date = new Date(str);
	date.setDate(date.getDate() + new Number(days));
	let year = date.getFullYear();
	let month = date.getMonth()+1;
	let day = date.getDate();
	if(month >= 1 && month <= 9) {
        month = "0" + month;
    }
	if(day >= 0 && day <= 9) {
		day = '0' + day;
	}
	return  year+"-"+ month+"-"+day;
}

module.exports = {
  uuid: uuid,
  toHexString: toHexString,
  dict: dict,
  request: request,
  isEmpty: isEmpty,
  isNotEmpty: isNotEmpty,
  getNextFormatDate: getNextFormatDate,
  getNextFormatNowDate: getNextFormatNowDate
}